package com.ctgu.project.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctgu.project.entity.BlogsEntity;
import com.ctgu.project.entity.UserFollowsEntity;
import com.ctgu.project.entity.UsersEntity;
import com.ctgu.project.mapper.UserFollowsMapper;
import com.ctgu.project.response.GetUserDTO;
import com.ctgu.project.service.BlogsService;
import com.ctgu.project.service.UserFollowsService;
import com.ctgu.project.service.UsersService;
import com.ctgu.project.utils.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Alex2
 * @description 针对表【t_users】的数据库操作Service实现
 * @createDate 2025-02-27 17:28:26
 */
@Service
public class UserFollowsServiceImpl extends ServiceImpl<UserFollowsMapper, UserFollowsEntity>
        implements UserFollowsService {

    private static final String REDIS_KEY_FOLLOW_USER = "follow:user:";
    private static final String REDIS_KEY_BLOG_FOLLOW = "blog:follow:";

    @Autowired
    private BlogsService blogsService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UsersService usersService;

    /**
     * @Author: Alex
     * @Description: 添加用户(模拟)
     */
    @Override
    public ApiResult addUsers() {
        UsersEntity usersEntity1 = new UsersEntity(null, "Alex", "123456", "13226782055");
        UsersEntity usersEntity2 = new UsersEntity(null, "Tom", "888888", "19168547825");
        UsersEntity usersEntity3 = new UsersEntity(null, "Jerry", "666666", "13081505603");
        List<UsersEntity> list = Arrays.asList(usersEntity1, usersEntity2, usersEntity3);
        ArrayList<UsersEntity> notExistUsers = new ArrayList<>();
        list.forEach(usersEntity -> {
            UsersEntity users = usersService.lambdaQuery().eq(UsersEntity::getUsername, usersEntity.getUsername()).one();
            if (users == null) {
                notExistUsers.add(usersEntity);
            }
        });
        if (notExistUsers.isEmpty()) {
            return ApiResult.success("所有用户均在数据库中，无新增用户");
        }
        notExistUsers.forEach(usersEntity -> {
            usersService.save(usersEntity);
        });
        return ApiResult.success("新增用户成功");
    }

    /**
     * @Author: Alex
     * @Description: 为用户添加粉丝(模拟)
     */
    @Override
    public ApiResult addFollows() {
        List<String> ids1 = Arrays.asList("Alex", "Tom", "Jerry");
        List<UsersEntity> follows1 = usersService.lambdaQuery().in(UsersEntity::getUsername, ids1).list();
        follows1.forEach(usersEntity -> {
            follow(1, usersEntity.getId());  //为用户1添加2、3、4作为粉丝
        });

        List<String> ids2 = Arrays.asList("Tom", "Jerry");
        List<UsersEntity> follows2 = usersService.lambdaQuery().in(UsersEntity::getUsername, ids2).list();
        follows2.forEach(usersEntity -> {
            follow(2, usersEntity.getId());  //为用户2添加3、4作为粉丝
        });

        return ApiResult.success("新增以下用户，并将其作为粉丝");
    }

    /**
     * @Author: Alex
     * @Description: 关注/取关
     */
    @Override
    public ApiResult follow(Integer userId, Integer followId) {
        boolean isFollowed = Boolean.TRUE.equals(redisTemplate.opsForSet().isMember(REDIS_KEY_FOLLOW_USER + userId, followId.toString()));
        if (!isFollowed) {
            UserFollowsEntity follow = new UserFollowsEntity(null, userId, followId);
            save(follow);
            redisTemplate.opsForSet().add(REDIS_KEY_FOLLOW_USER + userId, followId.toString());
            return ApiResult.success("关注成功");
        } else {
            UserFollowsEntity userFollowsEntity = lambdaQuery().
                    eq(UserFollowsEntity::getUserId, userId)
                    .eq(UserFollowsEntity::getFollowId, followId)
                    .one();
            removeById(userFollowsEntity);
            redisTemplate.opsForSet().remove(REDIS_KEY_FOLLOW_USER + userId, followId.toString());
            return ApiResult.success("取消关注成功");
        }
    }

    /**
     * @Author: Alex
     * @Description: 获取共同关注
     */
    @Override
    public ApiResult commons(Integer userId, Integer otherUserId) {
        Set<String> intersect = redisTemplate.opsForSet().intersect(REDIS_KEY_FOLLOW_USER + userId, REDIS_KEY_FOLLOW_USER + otherUserId);
        if (intersect == null || intersect.isEmpty()) {
            return ApiResult.success("共同关注列表为空", Collections.emptyList());
        }
        List<Integer> ids = intersect.stream().map(Integer::valueOf).collect(Collectors.toList());
        List<GetUserDTO> users = usersService.listByIds(ids)
                .stream()
                .map(user -> BeanUtil.copyProperties(user, GetUserDTO.class))
                .collect(Collectors.toList());
        return ApiResult.success("获取共同关注成功", users);
    }

    /**
     * @Author: Alex
     * @Description: 插入博客并将其推送给粉丝
     */
    @Override
    public ApiResult insertBlog(String title, Integer userId) {
        BlogsEntity blogsEntity = new BlogsEntity(null, title, userId, 0);
        boolean save = blogsService.save(blogsEntity);
        if (!save) {
            return ApiResult.success("博客发表失败", blogsEntity);
        }
        // 查询作者所有粉丝
        List<UserFollowsEntity> followsEntities = lambdaQuery().eq(UserFollowsEntity::getUserId, userId).list();
        if (followsEntities == null || followsEntities.isEmpty()) {
            return ApiResult.success("博主没有粉丝", Collections.emptyList());
        }
        // 推送博客id给所有粉丝
        for (UserFollowsEntity followsEntity : followsEntities) {
            Integer followsId = followsEntity.getFollowId();
            redisTemplate.opsForZSet().add(REDIS_KEY_BLOG_FOLLOW + followsId, blogsEntity.getId().toString(), System.currentTimeMillis());
        }
        return ApiResult.success("博客发表成功", blogsEntity);
    }
}